import { Component, OnInit, AfterViewChecked } from '@angular/core';
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
 // import ClassicEditor from '@ckeditor/ckeditor5-editor-classic';
import { ToastController } from '@ionic/angular';
import { ApiService } from '../api/api.service';
import { ApiUrl } from '../api/ApiUrl';
import { AnswerVO } from '../vo/Answervo';
import { UserVO } from '../vo/UserVO';
import { MyCustomUploadAdapterPlugin } from '../api/MyUploadAdapter';
import { ChangeEvent } from '@ckeditor/ckeditor5-angular/ckeditor.component';
import { Router } from '@angular/router';
@Component({
  selector: 'app-postmessage',
  templateUrl: './postmessage.page.html',
  styleUrls: ['./postmessage.page.scss'],
})
export class PostmessagePage implements OnInit, AfterViewChecked {
  public Editor = ClassicEditor;
  ctitle = '';
  cdesc = '';
  editorData = '';
  item: AnswerVO;
  userItem: UserVO;
  constructor(private router: Router, public api: ApiService, private toastController: ToastController) {
  }

  public onChange( { editor }: ChangeEvent ) {
    const data = editor.getData();

    console.log( data );
}


  ngOnInit() {
    this.userItem = ApiUrl.user;
    // this.Editor
    // .create( document.querySelector( '#editor' ), {
    //     // extraPlugins: [ MyCustomUploadAdapterPlugin ],
    //     toolbar: [ 'bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote' ]
    //     // ...
    // } )
    // .catch( error => {
    //     console.log( error );
    // } );
  }
  ngAfterViewChecked() {
    if (ApiUrl.user != null) {
      this.userItem = ApiUrl.user;
    } else {
      this.userItem = null;
    }
  }
  submit() {
    if (this.userItem === null) {
      this.router.navigate(['/login']);
      return;
    }
    if (this.ctitle.length === 0) {
      this.presentToast('请输入标题');
      return;
    }
    if (this.cdesc.length === 0) {
      this.presentToast('请输入摘要');
      return;
    }
    if (this.editorData.length === 0) {
      this.presentToast('请输入内容');
      return;
    }
    this.save();
  }
  save() {
    this.api.getItem<AnswerVO>(ApiUrl.toSaveArticle, {
      'ctitle': this.ctitle, 'icreator': this.userItem.iid,
      'cdesc': this.cdesc, 'ccontent': this.editorData
    }).subscribe(response => {

      this.item = response;
      if (this.item.success) {
        this.presentToast(this.item.msg);
        this.ctitle = '';
        this.cdesc = '';
        this.editorData = '';
      } else {
        this.presentToast(this.item.msg);
      }
    }, () => {
      console.log('出错了');
    });
  }
  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }
}
